from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
import os, time, json
from app01.models import *
from django.http import JsonResponse
from django.db.models import Count, Min, Max, Sum
from 开发发布 import settings
from django.core import serializers

basedir = settings.BASE_DIR
print(basedir)


# Create your views here.

def acc_login(request):
    if request.method == "POST":
        print(request.POST)
        user = authenticate(username=request.POST.get("username"), password=request.POST.get("password"))
        if user:
            login(request, user)
            return redirect(request.GET.get('next'))
        else:
            error = "error"
            return render(request, "login.html", {"login_error": error})
    print("用户正在访问登陆页")
    return render(request, "login.html")


@login_required
def acc_logout(requrst):
    logout(requrst)
    return redirect("/")


@login_required
def index(request):
    if request.is_ajax() and request.GET:
        text = request.GET['text']
        # 获取项目名称
        Branch = request.GET.get('Branch')
        # 获取分支
        q目标机器IP = 发布.objects.filter(目录名=text)
        目标机器IP = json.loads(serializers.serialize("json", q目标机器IP))
        目标机器IP = 目标机器IP[0]['fields']['目标机器IP']

        print("项目名称:", text, "分支:", Branch, "目标机器IP", 目标机器IP)
        logpath = os.path.join(basedir, "static/log")
        os.system("rm -rf {}".format(os.path.join(logpath, text + ".log")))
        if not os.path.isdir(logpath):
            os.makedirs(logpath)
        gitdown = os.path.join("/dxg/src/", text)

        commit = os.popen('''ssh %s "cd %s && git log|sed -n 1p|awk '{print $2}' " ''' % (目标机器IP, gitdown)).read()
        commit_info = os.popen('''ssh %s "cd %s && git log|sed -n 5p"''' % (目标机器IP, gitdown)).read()

        if Branch:
            # 切换分支
            #  git fetch
            # git checkout develop
            os.system(
                '''nohup ssh {} " cd {} && git fetch && git checkout {} && git branch" >{} 2>&1 &'''.format(
                    目标机器IP, gitdown, Branch,
                    os.path.join(logpath, text + ".log")))

        if text == 'dl':
            os.system(
                '''nohup ssh -p 23 121.201.87.148 "cd /dxg/dist/dl/ && git pull && echo release_ok && git log|sed -n 1,6p" >{} 2>&1 &'''.format(
                    os.path.join(logpath, text + ".log")))
        elif text == 'mma_test':
            os.system('''nohup ssh {} "/dxg/test/update_all.sh " >{} 2>&1 &'''.format(
                目标机器IP, os.path.join(logpath, text + ".log")))
        elif text == 'dxg-cuea-seo-ui':
            os.system('''nohup ssh {} "/dxg/src/cuea-seo-ui.sh " >{} 2>&1 &'''.format(
                目标机器IP, os.path.join(logpath, text + ".log")))
        elif text=='mma-guess-admin-ui':
            os.system('''nohup ssh {} "/dxg/src/mma-guess-admin-ui.sh" >{} 2>&1 &'''.format(
                目标机器IP, os.path.join(logpath, text + ".log")))
        # elif text=='mma-guess-ui':
        #     os.system('''nohup ssh {} "/dxg/src/mma-guess-ui.sh" >{} 2>&1 &'''.format(
        #         目标机器IP, os.path.join(logpath, text + ".log")))
        else:
            os.system(
                '''nohup ssh {} "/dxg/src/front.sh {} " >{} 2>&1 &'''.format(
                    目标机器IP, gitdown,
                    os.path.join(logpath, text + ".log")))

        发布统计.objects.get_or_create(项目名=text, 发布时间=time.strftime('%Y-%m-%d %H:%M'), commit=commit,
                                   commit_info=commit_info)
    data = 发布.objects.all()

    return render(request, 'index.html', {"data": data})


@login_required
def 发布统计_(request):
    开始时间 = time.strftime('%Y-%m-01')
    结束时间 = time.strftime('%Y-%m-30')
    if request.POST:
        # print(request.POST)
        开始时间 = request.POST.get('开始时间')
        结束时间 = request.POST.get('结束时间')
        print(开始时间, 结束时间)
    项目列表 = []
    全部数据 = []
    data = 发布统计.objects.filter(发布时间__gte=开始时间).filter(发布时间__lt=结束时间).values('项目名').annotate(c=Count('*'))
    for i in data:
        # print(i)
        # 项目列表.append(i.get('项目名'))
        项目列表.append("项目名称：{} 发布次数：{}".format(i.get('项目名'), i.get('c')))
        全部数据.append({'value': i.get('c'), 'name': "项目名称：{} 发布次数：{}".format(i.get('项目名'), i.get('c'))})

    return render(request, '发布统计饼.html', {"data": json.dumps([项目列表, 全部数据]), "开始时间": 开始时间, "结束时间": 结束时间})
